package jetpack.com.pzl.architecture;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import jetpack.com.pzl.R;

/**
 * 在 Fragment 之间共享数据
 */
public class FragmentDetail extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_fragment_detail, container, false);
        final TextView tv = view.findViewById(R.id.tvViewModelFragmentDetail);
        //scope范围是同一个activity的周期内， ViewModelProviders.of(context)
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.getData().observe(getViewLifecycleOwner(), new Observer<ItemInfo>() {
            @Override
            public void onChanged(ItemInfo itemInfo) {
                tv.setText(itemInfo.toString());
            }
        });
        return view;
    }

}
